/*
 * @Description: node服务 模拟简单接口数据
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-06-13 13:33:39
 * @LastEditors: lhl
 * @LastEditTime: 2021-06-14 14:57:17
 */

const Koa = require('koa')
const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const fs = require('fs')
const app = new Koa()
const router = new Router()

app.use(bodyParser())
app.use(router.routes())
app.use(router.allowedMethods())

router.post('/register', async ctx => {
  ctx.set('Access-Control-Allow-Origin', '*')
  console.log(ctx, 'sfff', ctx.request.body)
  let { name, username } = ctx.request.body
  if (!name && !username) {
    ctx.body = {
      msg: '不合法',
      code: 0
    }
    return
  }
  //生成token
  let token = jwt.sign({ name: name, username: username }, 'secret', { expiresIn: '1h' })
  // console.log(jwt.decode(token)) // 解密 token
  ctx.body = {
    token: token,
    code: 200,
    msg: '注册成功'
  }
})

router.post('/login', async ctx => {
  ctx.set('Access-Control-Allow-Origin', '*')
  console.log(ctx, 'sfff', ctx.request.body)
  let { username } = ctx.request.body
  //生成token
  let token = jwt.sign({ username: username }, 'secret', { expiresIn: '1h' })
  // console.log(jwt.decode(token)) // 解密 token
  ctx.body = {
    token: token,
    code: 200,
    msg: 'ok'
  }
})

router.get('/getMenu', async ctx => {
  ctx.set('Access-Control-Allow-Origin', '*')
  let rawdata = fs.readFileSync('menu.json')
  let { menuData } = JSON.parse(rawdata)
  ctx.body = {
    menuData,
    code: 200,
    msg: 'ok'
  }
})

app.listen(3000)
